package com.red.servlet;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.red.connetcion.Result;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@WebServlet(name = "UploadServlet", value = "/upload")
//设置文件的配置 最大文件大小为 10MB
@MultipartConfig(maxFileSize = 10*1024*1024)
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取PrintWriter对象
        PrintWriter writer = response.getWriter();

//        1.获取文件处理对象 Part类型
        Part f1 = request.getPart("f1");
//        2.指定上传文件 保存到服务器中
//        2.1实例化文件对象
        File file = new File("/Users/humeng/courseCode/javaForWeb/jsp_demo/src/main/webapp/images");
//        2.2判断路径文件夹是否存在
        if (!file.exists()){
//            不存在 则新建文件夹
            file.mkdir();
        }
//        2.3获得文件信息并上传
        String name = f1.getName();
//        System.out.println(name);
        String randomFileName = UUID.randomUUID().toString();
//        2.3.1 把文件写入到 file文件下的 + 操作系统的分隔符 + name
        if(name!=null){
            f1.write(file+File.separator+randomFileName+".png");
            Result ok = Result.ok("/Users/humeng/courseCode/javaForWeb/jsp_demo/src/main/webapp/images/" + randomFileName + ".png", "文件上传成功");
            String s = JSONUtil.toJsonStr(ok);
            writer.write(s);
//            writer.write("文件上传成功");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
